// components/z-form/zy-picker.js
const formCom = require('./zy-form-com');
const Nid = require('../../common/nid');
const { deepClone } = require('../../common/clone');

Component({
    options: {
        dynamicSlots: true, // 启用动态 slot
    },
    behaviors: [formCom],
    /**
     * 组件的属性列表
     */
    properties: {
        optgroup: {
            type: Object,
            value: {}
        }
    },


    data: {
        value: [],
        pickViewGroup: [],
        getItemCls(base, group) {
            let cls = base;
            if (group) {
                cls = cls +  ` ${base}-${group[0]}`
            }
            return cls
        }
    },

    methods: {
        addOption(extra = {}, nid = Nid()) {
            this.optionGroup.push([
                nid, extra
            ])
        },
        onChange(e) {
            let newVal = e.detail.value;
            let values = [];
            this.optionGroup.forEach((group, index) => {
                values.push(group[1].options[newVal[index]])
            });
            this.triggerEvent('change', {
                value: values
            })
            // console.log('onChange', e.detail, values);
        },
        setValues(newVal) {
            // console.log('ssssssssssssss', newVal);

            let indexArr = []

            this.optionGroup.forEach((group, index) => {
                let optIndex = group[1].options.findIndex(v => v === newVal[index])
                indexArr.push(optIndex)
            });

            this.setData({
                value: indexArr
            })

            console.log('indexArr', indexArr);
            
        }
    },

    lifetimes: {
        attached() {
            this.optionGroup =  []
            if (this.data.optgroup) {
                let group = deepClone(this.data.optgroup)
                Object.keys(group).forEach(key => {
                    this.addOption(group[key], key)
                })
            }
            this.setData({
                pickViewGroup:  this.optionGroup.slice(0)
            })
        }
    }
})